package jmine.tec.rpc.common.serialization.json;

import java.util.HashMap;
import java.util.Map;

import jmine.tec.json.JSON;
import jmine.tec.json.JSONObject;
import jmine.tec.json.JSONString;

/**
 * Conversor de JSON para Java e vice-versa
 * 
 * @author lundberg
 */
public class JSONMapConverter extends AbstractJSONObjectConverter<Map<String, Object>> implements JSONConverterStrategy {

    /**
     * {@inheritDoc}
     */
    public boolean matchesJava(Object object) {
        return object instanceof Map;
    }

    /**
     * {@inheritDoc}
     */
    @Override
    protected JSON objectType() {
        return new JSONString("map");
    }

    /**
     * {@inheritDoc}
     */
    @Override
    protected Map<String, Object> instantiate(JSONConversionContext context, JSON json) {
        return new HashMap<String, Object>();
    }

    /**
     * {@inheritDoc}
     */
    @Override
    protected void fillObject(JSONConversionContext context, JSON json, Map<String, Object> object) {
        for (String key : json.getPropertyNames()) {
            if (!this.isSpecialProperty(key)) {
                object.put(key, context.toJava(json.getProperty(key)));
            }
        }
    }

    /**
     * {@inheritDoc}
     */
    @Override
    protected void fillJSON(JSONConversionContext context, Object object, JSONObject json) {
        Map<?, ?> map = (Map<?, ?>) object;
        for (Object key : map.keySet()) {
            json.setProperty((String) key, context.toJSON(map.get(key)));
        }
    }
}
